//
//  UIControl+Extension.swift
//  TestDemo
//
//  Created by ayin on 2019/3/20.
//  Copyright © 2019 aYin. All rights reserved.
//

import Foundation

extension String {
    // 获取文件大小
    func getFileSize(_ sizeBlock: @escaping ((UInt64?,Error?) -> Void)) {
        var size: UInt64 = 0
        let fileManager = FileManager.default
        var isDir: ObjCBool = false
        let isExists = fileManager.fileExists(atPath: self, isDirectory: &isDir)
        // 判断文件存在
        if isExists {
            // 是否为文件夹
            if isDir.boolValue {
                // 迭代器 存放文件夹下的所有文件名
                let enumerator = fileManager.enumerator(atPath: self)
                for subPath in enumerator! {
                    // 获得全路径
                    let fullPath = self.appending("/\(subPath)")
                    do {
                        let attr = try fileManager.attributesOfItem(atPath: fullPath)
                        size += attr[FileAttributeKey.size] as! UInt64
                        sizeBlock(size, nil)
                    } catch  {
                        sizeBlock(nil, error)
                    }
                }
            } else {    // 单文件
                do {
                    let attr = try fileManager.attributesOfItem(atPath: self)
                    size += attr[FileAttributeKey.size] as! UInt64
                    sizeBlock(size, nil)
                } catch  {
                    sizeBlock(nil, error)
                }
            }
        }
    }
}

extension  UIView
{
    /// 边框
    func border(_ color:UIColor,width:CGFloat)
    {
        self.layer.borderColor = color.cgColor
        self.layer.borderWidth = width
    }
    
    
    /// 圆角
    func cornerRadius(_ radius:CGFloat)
    {
        self.layer.masksToBounds = true
        self.layer.cornerRadius = radius
    }
}

/// iphone6屏幕宽度标准
let defaultWidth: CGFloat = 375.0

/// 适配所有屏的拉伸值
var adaptAllSizeScale: CGFloat = {
    let scale = screenWidth / defaultWidth
    return scale
}()

/// 适配大屏的拉伸值
var adaptBigScreenSizeScale:CGFloat = {
    var scale:CGFloat = 1.0
    if screenWidth > defaultWidth {
        scale = screenWidth / defaultWidth
    }
    
    return scale
}()

extension Int {
    /// 适配所有屏的控件尺寸
    var all: CGFloat {
        return adaptAllSizeScale * CGFloat.init(self)
    }
    
    /// 适配大屏的控件尺寸
    var up: CGFloat {
        return adaptBigScreenSizeScale * CGFloat.init(self)
    }
}

extension CGFloat {
    /// 适配所有屏的控件尺寸
    var all: CGFloat {
        return adaptAllSizeScale * CGFloat.init(self)
    }
    
    /// 适配大屏的控件尺寸
    var up: CGFloat {
        return adaptBigScreenSizeScale * CGFloat.init(self)
    }
}

extension Double {
    /// 适配所有屏的控件尺寸
    var all: CGFloat {
        return adaptAllSizeScale * CGFloat.init(self)
    }
    
    /// 适配大屏的控件尺寸
    var up: CGFloat {
        return adaptBigScreenSizeScale * CGFloat.init(self)
    }
}

extension  UIColor
{
    /// rgb 颜色生成
    ///
    /// - Parameters:
    ///   - r: r
    ///   - g: g
    ///   - b: b
    ///   - alpha: 透明
    /// - Returns: color
    class func colorWithCustom(_ r: CGFloat, g:CGFloat, b:CGFloat, alpha : CGFloat = 1) -> UIColor {
        return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: alpha)
    }
    
    
    /// 随机色生成
    ///
    /// - Returns: 随机color
    class func randomColor() -> UIColor {
        let r = CGFloat(arc4random_uniform(256))
        let g = CGFloat(arc4random_uniform(256))
        let b = CGFloat(arc4random_uniform(256))
        return UIColor.colorWithCustom(r, g: g, b: b)
    }
    
    /// 16进制颜色生成
    ///
    /// - Parameters:
    ///   - hex: 16进制
    ///   - alpha: 透明度
    /// - Returns: color
    class func colorWithHexString (_ hex:String, alpha: CGFloat = 1.0)-> UIColor {
        var formatted = hex.replacingOccurrences(of: "0x", with: "")
        formatted = formatted.replacingOccurrences(of: "#", with: "")
        if let hex = Int(formatted, radix: 16) {
            let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
            let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
            let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
            return UIColor(red: red, green: green, blue: blue, alpha: alpha)
            
        } else {
            return UIColor.white
        }
        
    }
}

extension UILabel{
    
    /// 创建一个Label
    ///
    /// - Parameters:
    ///   - font: 字体
    ///   - text: 文字
    ///   - textColor: 文字颜色，默认 333333
    ///   - numberLine: 文本行数，默认一行
    ///   - alignment: 对其方式，默认左对齐
    class func makeLabel(font: UIFont?,
                         text: String?,
                         textColor:UIColor,
                         numberLine: Int = 1,
                         alignment:NSTextAlignment = .left) -> UILabel {
        
        let label = UILabel()
        label.textColor = textColor
        label.numberOfLines = numberLine
        label.text = text
        label.textAlignment = alignment
        if let font = font {
            label.font = font
        }
        label.sizeToFit()
        
        return label
    }
    
    /// 设置富文本
    ///
    /// - Parameters:
    ///   - subString: 指定str
    ///   - color: 颜色
    ///   - font: 字体
    ///   - isUnderline: 是否加下划线
    ///   - isObliqueness: 是否斜体
    func attributedString(_ subString:String,color:UIColor,font:UIFont,isUnderline:Bool = false,isObliqueness:Bool = false) {
        guard  let text = self.text else{ debugPrint("字符串不能为空"); return}
        let subStrs = text.components(separatedBy: subString)
        var rangs = [NSRange]()
        for i in  0..<subStrs.count{
            var loc:Int = subStrs[i].count
            for j in 0..<i {
                loc = loc + subStrs[j].count + subString.count
            }
            let rang = NSMakeRange(loc, subString.count)
            
            rangs.append(rang)
        }
        
        var dic:[NSAttributedString.Key:Any] = [:]
        if isUnderline {
            if isObliqueness {
                dic = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:color,NSAttributedString.Key.underlineStyle:NSNumber(value: 1),NSAttributedString.Key.obliqueness:0.7]
            }else {
                dic = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:color,NSAttributedString.Key.underlineStyle:NSNumber(value: 1)]
            }
        }else {
            if isObliqueness {
                dic = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:color,NSAttributedString.Key.obliqueness:0.7]
            }else {
                dic = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:color]
            }
        }
        
        var attributedString  =  NSMutableAttributedString(string:self.text!)
        if self.attributedText != nil {
            attributedString  = NSMutableAttributedString(attributedString: self.attributedText!)
        }
        for rang in rangs {
            if attributedString.length >= rang.location + rang.length{
                attributedString.addAttributes(dic, range: rang)
                self.attributedText = attributedString
            }
        }
    }
    
    func addDeleteLine(_ lineColor: UIColor = UIColor.lightGray) {
        guard let text = self.text else {return}
        let length = text.count
        let attributedString = NSMutableAttributedString(string:text)
        attributedString.addAttribute(NSAttributedString.Key.baselineOffset, value: 0, range: NSMakeRange(0, length))
        attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: NSMakeRange(0, length))
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: lineColor, range: NSRange(location:0,length:length))
        self.attributedText = attributedString
    }
}

extension UIButton {
    /// 创建一个按钮
    ///
    /// - Parameters:
    ///   - font: 字体
    ///   - title: 标题
    ///   - titleColor: 标题颜色，默认颜色 333333
    ///   - image: 图片
    ///   - bgColor: 背景颜色，默认透明
    class func makeButton(font: UIFont?,
                          title: String?,
                          titleColor: UIColor = UIColor.black,
                          image: String?,
                          bgColor:UIColor = UIColor.clear) -> UIButton{
        let button = UIButton(type: .custom)
        button.titleLabel?.font = font
        button.setTitle(title, for: .normal)
        button.setTitleColor(titleColor, for: .normal)
        if let image = image{
            button.setImage(UIImage(named: image) , for: .normal)
        }
        button.sizeToFit()
        button.backgroundColor = bgColor
        return button
    }
    
    func zoomAnimation() {
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.duration = 0.5//动画持续时间
        animation.repeatCount = HUGE//重复次数(无限)
        animation.autoreverses = true//动画结束时执行逆动画
        animation.fromValue = 0.95//开始时的倍率
        animation.toValue = 1.05//结束时的倍率
        self.layer.add(animation, forKey: "scale-layer")
    }
}

extension UIView {
    ///  - 添加虚线
    func dottedLineView(_ lineColor: UIColor = UIColor.lightGray, lineWidth : CGFloat = 1.0,lineDashPattern : [NSNumber] = [4,3] )  {
        let border             = CAShapeLayer()
        border.strokeColor     = lineColor.cgColor
        border.fillColor       = nil
        let path =  UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: self.width, y: 0))
        
        border.path            = path.cgPath
        border.frame           = self.bounds
        border.lineCap         = CAShapeLayerLineCap(rawValue: "square")
        border.lineWidth       = lineWidth
        border.lineDashPattern = lineDashPattern
        self.layer.addSublayer(border)
    }
}

extension String {
    /*
     * example: ￥100
     * priceLb.attributedText = String.addAttributeString(prefixString: "￥", contentString: "100", prefixFont: UIFont.pingfangSemibold(size: 28.all)!, contentFont: UIFont.dinot(size: 28.all)!)
     * desc: 添加文字富文本
     */
    
    /// Add AttributeString like (￥100) with different prefix font and different content font
    ///
    /// - Parameters:
    ///   - prefixString: what prefix you want
    ///   - contentString: what content you want
    ///   - prefixFont: prefix font
    ///   - contentFont: content font
    /// - Returns: return NSMutableAttributedString object
    static public func addAttributeString(prefixString: String,contentString: String,prefixFont: UIFont,contentFont: UIFont) -> NSMutableAttributedString {
        let commonString = prefixString + contentString
        let prefixRange = NSString.init(string: commonString).range(of: prefixString)
        let contentRange = NSString.init(string: commonString).range(of: contentString)
        let attributedString = NSMutableAttributedString(string: commonString)
        attributedString.addAttributes([NSAttributedString.Key.font : prefixFont], range: prefixRange)
        attributedString.addAttributes([NSAttributedString.Key.font : contentFont], range: contentRange)
        return attributedString
    }
    //添加颜色 ...
    
    /// Add AttributeString like (￥100) with different prefix color and content color
    ///
    /// - Parameters:
    ///   - prefixString: what prefix you want
    ///   - contentString: what content you want
    ///   - prefixColor: prefixColor
    ///   - contentColor: contentColor
    /// - Returns: return NSMutableAttributedString object
    static public func addAttributeStringForegroundColor(prefixString: String,contentString: String,prefixColor: UIColor,contentColor: UIColor) -> NSMutableAttributedString {
        let commonString = prefixString + contentString
        let prefixRange = NSString.init(string: commonString).range(of: prefixString)
        let contentRange = NSString.init(string: commonString).range(of: contentString)
        let attributedString = NSMutableAttributedString(string: commonString)
        attributedString.addAttributes([NSAttributedString.Key.foregroundColor : prefixColor], range: prefixRange)
        attributedString.addAttributes([NSAttributedString.Key.foregroundColor : contentColor], range: contentRange)
        return attributedString
    }
    
    
    /// 设置行间距富文本(适用于多行文本，但需调整行间距的情况）
    ///
    /// - Parameters:
    ///   - lineSpace: 行间距
    ///   - color: 颜色
    ///   - font: 字体
    ///   - alignment: 文本对齐方式：（左，中，右）
    /// - Returns: 富文本
    func addAttributeString(lineSpace: CGFloat, color: UIColor, font: UIFont, alignment: NSTextAlignment = .center) ->NSAttributedString {
        let attributeString = NSMutableAttributedString(string: self)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpace
        paragraphStyle.alignment = alignment
        let attribute = [
            NSAttributedString.Key.font : font,
            NSAttributedString.Key.paragraphStyle : paragraphStyle,
        ]
        attributeString.addAttributes(attribute, range: NSMakeRange(0, self.count))
        return attributeString
    }
    
    func boundingRect(with constrainedSize: CGSize, font: UIFont, lineSpacing: CGFloat? = nil) -> CGSize {
        let attritube = NSMutableAttributedString(string: self)
        let range = NSRange(location: 0, length: attritube.length)
        attritube.addAttributes([NSAttributedString.Key.font: font], range: range)
        if lineSpacing != nil {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = lineSpacing!
            attritube.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: range)
        }
        
        let rect = attritube.boundingRect(with: constrainedSize, options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
        var size = rect.size
        
        if let currentLineSpacing = lineSpacing {
            // 文本的高度减去字体高度小于等于行间距，判断为当前只有1行
            let spacing = size.height - font.lineHeight
            if spacing <= currentLineSpacing && spacing > 0 {
                size = CGSize(width: size.width, height: font.lineHeight)
            }
        }
        
        return size
    }
    
    func boundingRect(with constrainedSize: CGSize, font: UIFont, lineSpacing: CGFloat? = nil, lines: Int) -> CGSize {
        if lines < 0 {
            return .zero
        }
        
        let size = boundingRect(with: constrainedSize, font: font, lineSpacing: lineSpacing)
        if lines == 0 {
            return size
        }
        
        let currentLineSpacing = (lineSpacing == nil) ? (font.lineHeight - font.pointSize) : lineSpacing!
        let maximumHeight = font.lineHeight*CGFloat(lines) + currentLineSpacing*CGFloat(lines - 1)
        if size.height >= maximumHeight {
            return CGSize(width: size.width, height: maximumHeight)
        }
        
        return size
    }
}

